//
//  QGAdHocListController.m
//  RepairFactory
//
//  Created by heew on 15/12/5.
//  Copyright © 2015年 qeegoo. All rights reserved.
//

#import "QGAdHocListController.h"
#import "QGAdhocCell.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"

@interface QGAdHocListController () <UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *adhocList; /**测试版本列表 */
@end

@implementation QGAdHocListController
- (NSMutableArray *)adhocList {
    if (_adhocList == nil) {
        _adhocList = [NSMutableArray array];
    }
    return _adhocList;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"内测版本列表";
    self.tabBarItem.title = @"下载";
    self.tabBarItem.image = [UIImage imageNamed:@"download"];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView.header beginRefreshing];
}

- (void)loadNewData
{
    [self.adhocList removeAllObjects];
    [self.tableView reloadData];
    
    NSMutableArray *mutableOperations = [NSMutableArray array];
    NSDictionary *param1 = @{@"aId" : @"763c02c118282e25e9d8293a1c9e0916",
                            @"_api_key" : @"0f100573a132929b1fc0abc9d3e72615"};
    NSMutableURLRequest *request1 = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST"
                                                                                  URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                                                                 parameters:param1
                                                                                      error:nil];
    AFHTTPRequestOperation *op1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
    [mutableOperations addObject:op1];
    
    NSDictionary *param2 = @{@"aId" : @"7e40b240a17f3a8fef2f7df285830826",
                             @"_api_key" : @"0f100573a132929b1fc0abc9d3e72615"};
    NSMutableURLRequest *request2 = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST"
                                                                                  URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                                                                 parameters:param2
                                                                                      error:nil];
    AFHTTPRequestOperation *op2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
    [op2 addDependency:op1];
    [mutableOperations addObject:op2];
    
    NSDictionary *param3 = @{@"aId" : @"7e5731a1622381f114e0d12f09f57200",
                             @"_api_key" : @"0f100573a132929b1fc0abc9d3e72615"};
    NSMutableURLRequest *request3 = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST"
                                                                                  URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                                                                 parameters:param3
                                                                                      error:nil];
    AFHTTPRequestOperation *op3 = [[AFHTTPRequestOperation alloc] initWithRequest:request3];
    [op3 addDependency:op2];
    [mutableOperations addObject:op3];
    
    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
         NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
    } completionBlock:^(NSArray *operations) {
        for (AFURLConnectionOperation *operation in operations) {
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                                           options:NSJSONReadingMutableLeaves
                                                                             error:nil];
            for (NSDictionary *dict in responseObject[@"data"]) {
                QGAdHocApp *app = [QGAdHocApp appWithDictionary:dict];
                [self.adhocList addObject:app];
            }
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    }];
    [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];}
#pragma mark - tableView datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.adhocList.count;
}

// 每一个行的细节
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QGAdhocCell *cell = [QGAdhocCell cellWithTableView:tableView];
    QGAdHocApp *app = self.adhocList[indexPath.row];
    cell.app = app;
    return cell;
}
#pragma mark - tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    QGAdHocApp *app = self.adhocList[indexPath.row];
    NSString *appUrlString = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=https://www.pgyer.com/app/plist/%@",app.appKey];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrlString]];
//    [SVProgressHUD showSuccessWithStatus:@"已经开始安装,按home查看安装进度"];
}
@end

@implementation QGAdHocApp
+ (instancetype)appWithDictionary:(NSDictionary *)dict {
    QGAdHocApp *app = [[QGAdHocApp alloc] init];
    [app setValuesForKeysWithDictionary:dict];
    return app;
}
@end
